package com.zl.learning.io;

import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.concurrent.TimeUnit;

public class TestShutdownHook {
    public static void main(String[] args) {
        final Path basedir = FileSystems.getDefault().getPath("D:/work/tmp/");
        final String tmp_dir_prefix = "rafa_";
        try {
            final Path tmp_dir = Files.createTempDirectory(basedir, tmp_dir_prefix);
            Runtime.getRuntime().addShutdownHook(new Thread() {
                @Override
                public void run() {
                    System.out.println("Deleting the temporary folder ...");
                    try (DirectoryStream<Path> ds = Files.newDirectoryStream(tmp_dir)) {
                        for (Path file : ds) {
                            Files.delete(file);
                        }
                        Files.delete(tmp_dir);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    System.out.println("Shutdown-hook completed...");
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            TimeUnit.SECONDS.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
